package com.xcity.game.employee.config.impl;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.xcity.db.entity.Employee;
import com.xcity.db.entity.Player;
import com.xcity.game.employee.EmployeeQuality;
import com.xcity.game.employee.EmployeeService;
import com.xcity.game.employee.config.AbstractConfigure;
import com.xcity.game.employee.config.Configure;
import com.xcity.game.employee.template.EmployeeTemplate;

import gnu.trove.map.TIntObjectMap;
import naga.x.App;
import naga.x.game.template.TemplateService;

/**
 * 员工配置
 * @author yang.li
 *
 */
public class EmployeeTemplateConfigure extends AbstractConfigure {

	protected TIntObjectMap<EmployeeTemplate> templates;
	protected Map<EmployeeQuality, List<EmployeeTemplate>> qualityToEmployeeTemplates;
	protected Map<Integer, EmployeeTemplate> piecesMap;
	
	public EmployeeTemplateConfigure(Configure parent) {
		super(parent);
	}
	
	@Override
	public EmployeeTemplateConfigure configure() {
		TIntObjectMap<EmployeeTemplate> templates = App.getApp().getServiceManager().get(TemplateService.class).getTemplates(EmployeeTemplate.class);
		Map<EmployeeQuality, List<EmployeeTemplate>> qualityToEmployeeTemplates = new EnumMap<>(EmployeeQuality.class);
		Map<Integer, EmployeeTemplate> piecesMap = new LinkedHashMap<>();
		List<EmployeeTemplate> employeeTemplates = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(EmployeeTemplate.class);
		for (int i = 0, size = employeeTemplates.size(); i < size; i++) {
			EmployeeTemplate temp = employeeTemplates.get(i);
			if (temp.isObsolete()) {
				continue;
			}
			List<EmployeeTemplate> list = qualityToEmployeeTemplates.get(temp.getQuality());
			if (list == null) {
				list = new ArrayList<>();
				qualityToEmployeeTemplates.put(temp.getQuality(), list);
			}
			list.add(temp);
			if (temp.getPieceId() > 0 && temp.getPieceCount() > 0) {
				piecesMap.put(temp.getPieceId(), temp);
			}
		}
		
		this.templates = templates;
		this.qualityToEmployeeTemplates = qualityToEmployeeTemplates;
		this.piecesMap = piecesMap;
		
		return this;
	}

	public Map<Integer, EmployeeTemplate> getPiecesMap() {
		return piecesMap;
	}
	
	public EmployeeTemplate findTemplate(int id) {
		return templates.get(id);
	}
	
	/**
	 * 按品质掉落一个员工
	 * @param player
	 * @param quality
	 */
	public Employee dropByQuality(Player player, EmployeeQuality quality, String cause) {
		List<EmployeeTemplate> list = qualityToEmployeeTemplates.get(quality);
		if (list != null && !list.isEmpty()) {
			EmployeeTemplate template = list.get(EmployeeService.RND.nextInt(list.size()));
			Employee employee = new Employee(template, player.getEmployees(), parent());
			player.getEmployees().addEmployee(employee, true, cause);
		}
		return null;
	}
	
}
